<template>
  <div class="app-container">
    <!-- 系统概览卡片 -->
    <div class="stats-container">
      <StatCard
        title="系统运行时间"
        :value="systemInfo.uptime || 0"
        icon="Timer"
        type="primary"
        suffix="天"
      />
      <StatCard
        title="CPU使用率"
        :value="systemInfo.cpuUsage || 0"
        icon="Cpu"
        type="success"
        suffix="%"
      />
      <StatCard
        title="内存使用率"
        :value="systemInfo.memoryUsage || 0"
        icon="Memory"
        type="warning"
        suffix="%"
      />
      <StatCard
        title="磁盘使用率"
        :value="systemInfo.diskUsage || 0"
        icon="HardDrive"
        type="danger"
        suffix="%"
      />
    </div>
    
    <!-- 系统监控图表 -->
    <div class="chart-container">
      <div class="chart-row">
        <!-- CPU使用率趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">CPU使用率趋势</div>
            <div class="chart-actions">
              <el-radio-group v-model="cpuTimeRange" size="small" @change="handleCpuTimeRangeChange">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="6h">6小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="cpuChartRef"
              :options="cpuChartOptions"
              :loading="cpuChartLoading"
              height="300px"
            />
          </div>
        </div>
        
        <!-- 内存使用率趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">内存使用率趋势</div>
            <div class="chart-actions">
              <el-radio-group v-model="memoryTimeRange" size="small" @change="handleMemoryTimeRangeChange">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="6h">6小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="memoryChartRef"
              :options="memoryChartOptions"
              :loading="memoryChartLoading"
              height="300px"
            />
          </div>
        </div>
      </div>
      
      <div class="chart-row">
        <!-- 磁盘使用率趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">磁盘使用率趋势</div>
            <div class="chart-actions">
              <el-radio-group v-model="diskTimeRange" size="small" @change="handleDiskTimeRangeChange">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="6h">6小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="diskChartRef"
              :options="diskChartOptions"
              :loading="diskChartLoading"
              height="300px"
            />
          </div>
        </div>
        
        <!-- 网络流量趋势 -->
        <div class="chart-card">
          <div class="chart-header">
            <div class="chart-title">网络流量趋势</div>
            <div class="chart-actions">
              <el-radio-group v-model="networkTimeRange" size="small" @change="handleNetworkTimeRangeChange">
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="6h">6小时</el-radio-button>
                <el-radio-button label="24h">24小时</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div class="chart-content">
            <ChartContainer
              ref="networkChartRef"
              :options="networkChartOptions"
              :loading="networkChartLoading"
              height="300px"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 系统信息表格 -->
    <div class="info-container">
      <div class="info-row">
        <!-- 系统基本信息 -->
        <Card title="系统基本信息" class="info-card">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="操作系统">{{ systemInfo.osName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="系统版本">{{ systemInfo.osVersion || '-' }}</el-descriptions-item>
            <el-descriptions-item label="Java版本">{{ systemInfo.javaVersion || '-' }}</el-descriptions-item>
            <el-descriptions-item label="JVM版本">{{ systemInfo.jvmVersion || '-' }}</el-descriptions-item>
            <el-descriptions-item label="服务器IP">{{ systemInfo.serverIp || '-' }}</el-descriptions-item>
            <el-descriptions-item label="启动时间">{{ systemInfo.startTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="运行时间">{{ systemInfo.uptime ? `${systemInfo.uptime}天` : '-' }}</el-descriptions-item>
            <el-descriptions-item label="时区">{{ systemInfo.timezone || '-' }}</el-descriptions-item>
          </el-descriptions>
        </Card>
        
        <!-- JVM信息 -->
        <Card title="JVM信息" class="info-card">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="JVM名称">{{ systemInfo.jvmName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="JVM供应商">{{ systemInfo.jvmVendor || '-' }}</el-descriptions-item>
            <el-descriptions-item label="最大内存">{{ formatBytes(systemInfo.maxMemory) }}</el-descriptions-item>
            <el-descriptions-item label="已分配内存">{{ formatBytes(systemInfo.totalMemory) }}</el-descriptions-item>
            <el-descriptions-item label="空闲内存">{{ formatBytes(systemInfo.freeMemory) }}</el-descriptions-item>
            <el-descriptions-item label="已使用内存">{{ formatBytes(systemInfo.usedMemory) }}</el-descriptions-item>
            <el-descriptions-item label="内存使用率">{{ systemInfo.memoryUsage || 0 }}%</el-descriptions-item>
            <el-descriptions-item label="线程数">{{ systemInfo.threadCount || 0 }}</el-descriptions-item>
          </el-descriptions>
        </Card>
      </div>
      
      <div class="info-row">
        <!-- CPU信息 -->
        <Card title="CPU信息" class="info-card">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="CPU核心数">{{ systemInfo.cpuCores || 0 }}</el-descriptions-item>
            <el-descriptions-item label="CPU线程数">{{ systemInfo.cpuThreads || 0 }}</el-descriptions-item>
            <el-descriptions-item label="CPU型号">{{ systemInfo.cpuModel || '-' }}</el-descriptions-item>
            <el-descriptions-item label="CPU频率">{{ systemInfo.cpuFrequency || '-' }}</el-descriptions-item>
            <el-descriptions-item label="CPU使用率">{{ systemInfo.cpuUsage || 0 }}%</el-descriptions-item>
            <el-descriptions-item label="系统负载">{{ systemInfo.systemLoad || 0 }}</el-descriptions-item>
          </el-descriptions>
        </Card>
        
        <!-- 内存信息 -->
        <Card title="内存信息" class="info-card">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="总内存">{{ formatBytes(systemInfo.totalPhysicalMemory) }}</el-descriptions-item>
            <el-descriptions-item label="可用内存">{{ formatBytes(systemInfo.freePhysicalMemory) }}</el-descriptions-item>
            <el-descriptions-item label="已使用内存">{{ formatBytes(systemInfo.usedPhysicalMemory) }}</el-descriptions-item>
            <el-descriptions-item label="内存使用率">{{ systemInfo.memoryUsage || 0 }}%</el-descriptions-item>
            <el-descriptions-item label="交换区总大小">{{ formatBytes(systemInfo.totalSwapSpace) }}</el-descriptions-item>
            <el-descriptions-item label="交换区可用大小">{{ formatBytes(systemInfo.freeSwapSpace) }}</el-descriptions-item>
          </el-descriptions>
        </Card>
      </div>
      
      <div class="info-row">
        <!-- 磁盘信息 -->
        <Card title="磁盘信息" class="info-card">
          <el-table :data="diskInfo" style="width: 100%">
            <el-table-column prop="name" label="磁盘名称" width="180" />
            <el-table-column prop="type" label="文件系统类型" width="120" />
            <el-table-column prop="total" label="总大小">
              <template #default="{ row }">
                {{ formatBytes(row.total) }}
              </template>
            </el-table-column>
            <el-table-column prop="free" label="可用空间">
              <template #default="{ row }">
                {{ formatBytes(row.free) }}
              </template>
            </el-table-column>
            <el-table-column prop="used" label="已用空间">
              <template #default="{ row }">
                {{ formatBytes(row.used) }}
              </template>
            </el-table-column>
            <el-table-column prop="usage" label="使用率">
              <template #default="{ row }">
                <el-progress :percentage="row.usage" :color="getUsageColor(row.usage)" />
              </template>
            </el-table-column>
          </el-table>
        </Card>
      </div>
    </div>
    
    <!-- 刷新按钮 -->
    <div class="refresh-container">
      <el-button type="primary" @click="refreshData" :loading="refreshing">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { getSystemInfo, getSystemMonitorData } from '@/api/system'
import { ChartContainer } from '@/components/common'

// 系统信息
const systemInfo = reactive({
  osName: '',
  osVersion: '',
  javaVersion: '',
  jvmVersion: '',
  jvmName: '',
  jvmVendor: '',
  maxMemory: 0,
  totalMemory: 0,
  freeMemory: 0,
  usedMemory: 0,
  memoryUsage: 0,
  threadCount: 0,
  cpuCores: 0,
  cpuThreads: 0,
  cpuModel: '',
  cpuFrequency: '',
  cpuUsage: 0,
  systemLoad: 0,
  totalPhysicalMemory: 0,
  freePhysicalMemory: 0,
  usedPhysicalMemory: 0,
  totalSwapSpace: 0,
  freeSwapSpace: 0,
  diskUsage: 0,
  serverIp: '',
  startTime: '',
  uptime: 0,
  timezone: ''
})

// 磁盘信息
const diskInfo = ref([])

// 图表相关
const cpuChartRef = ref(null)
const memoryChartRef = ref(null)
const diskChartRef = ref(null)
const networkChartRef = ref(null)
const cpuChartLoading = ref(false)
const memoryChartLoading = ref(false)
const diskChartLoading = ref(false)
const networkChartLoading = ref(false)
const cpuChartOptions = ref({})
const memoryChartOptions = ref({})
const diskChartOptions = ref({})
const networkChartOptions = ref({})

// 时间范围
const cpuTimeRange = ref('1h')
const memoryTimeRange = ref('1h')
const diskTimeRange = ref('1h')
const networkTimeRange = ref('1h')

// 其他变量
const refreshing = ref(false)
let refreshTimer = null

// 格式化字节数
const formatBytes = (bytes, decimals = 2) => {
  if (bytes === 0) return '0 Bytes'
  
  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
}

// 获取使用率颜色
const getUsageColor = (percentage) => {
  if (percentage < 50) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 获取系统信息
const getSystemInfoData = async () => {
  try {
    const response = await getSystemInfo()
    if (response) {
      Object.assign(systemInfo, response)
      
      // 处理磁盘信息
      if (response.diskInfo) {
        diskInfo.value = response.diskInfo
      }
    }
  } catch (error) {
    console.error('获取系统信息失败', error)
  }
}

// 获取图表数据
const getChartData = async (type, timeRange) => {
  try {
    switch (type) {
      case 'cpu':
        cpuChartLoading.value = true
        break
      case 'memory':
        memoryChartLoading.value = true
        break
      case 'disk':
        diskChartLoading.value = true
        break
      case 'network':
        networkChartLoading.value = true
        break
    }
    
    const response = await getSystemMonitorData({ type, timeRange })
    
    if (response && response.data) {
      const chartData = response.data
      
      switch (type) {
        case 'cpu':
          cpuChartOptions.value = {
            xAxis: {
              type: 'category',
              data: chartData.timestamps || []
            },
            yAxis: {
              type: 'value',
              min: 0,
              max: 100,
              axisLabel: {
                formatter: '{value}%'
              }
            },
            series: [
              {
                name: 'CPU使用率',
                type: 'line',
                smooth: true,
                data: chartData.values || [],
                areaStyle: {
                  color: 'rgba(103, 194, 58, 0.2)'
                },
                lineStyle: {
                  color: '#67c23a'
                }
              }
            ]
          }
          break
        case 'memory':
          memoryChartOptions.value = {
            xAxis: {
              type: 'category',
              data: chartData.timestamps || []
            },
            yAxis: {
              type: 'value',
              min: 0,
              max: 100,
              axisLabel: {
                formatter: '{value}%'
              }
            },
            series: [
              {
                name: '内存使用率',
                type: 'line',
                smooth: true,
                data: chartData.values || [],
                areaStyle: {
                  color: 'rgba(230, 162, 60, 0.2)'
                },
                lineStyle: {
                  color: '#e6a23c'
                }
              }
            ]
          }
          break
        case 'disk':
          diskChartOptions.value = {
            xAxis: {
              type: 'category',
              data: chartData.timestamps || []
            },
            yAxis: {
              type: 'value',
              min: 0,
              max: 100,
              axisLabel: {
                formatter: '{value}%'
              }
            },
            series: [
              {
                name: '磁盘使用率',
                type: 'line',
                smooth: true,
                data: chartData.values || [],
                areaStyle: {
                  color: 'rgba(245, 108, 108, 0.2)'
                },
                lineStyle: {
                  color: '#f56c6c'
                }
              }
            ]
          }
          break
        case 'network':
          networkChartOptions.value = {
            xAxis: {
              type: 'category',
              data: chartData.timestamps || []
            },
            yAxis: {
              type: 'value',
              axisLabel: {
                formatter: function(value) {
                  if (value >= 1024 * 1024 * 1024) {
                    return (value / (1024 * 1024 * 1024)).toFixed(2) + ' GB/s'
                  } else if (value >= 1024 * 1024) {
                    return (value / (1024 * 1024)).toFixed(2) + ' MB/s'
                  } else if (value >= 1024) {
                    return (value / 1024).toFixed(2) + ' KB/s'
                  }
                  return value + ' B/s'
                }
              }
            },
            series: [
              {
                name: '入站流量',
                type: 'line',
                smooth: true,
                data: chartData.inValues || [],
                areaStyle: {
                  color: 'rgba(24, 144, 255, 0.2)'
                },
                lineStyle: {
                  color: '#1890ff'
                }
              },
              {
                name: '出站流量',
                type: 'line',
                smooth: true,
                data: chartData.outValues || [],
                areaStyle: {
                  color: 'rgba(245, 108, 108, 0.2)'
                },
                lineStyle: {
                  color: '#f56c6c'
                }
              }
            ]
          }
          break
      }
    }
  } catch (error) {
    console.error(`获取${type}图表数据失败`, error)
  } finally {
    switch (type) {
      case 'cpu':
        cpuChartLoading.value = false
        break
      case 'memory':
        memoryChartLoading.value = false
        break
      case 'disk':
        diskChartLoading.value = false
        break
      case 'network':
        networkChartLoading.value = false
        break
    }
  }
}

// 处理CPU时间范围变化
const handleCpuTimeRangeChange = () => {
  getChartData('cpu', cpuTimeRange.value)
}

// 处理内存时间范围变化
const handleMemoryTimeRangeChange = () => {
  getChartData('memory', memoryTimeRange.value)
}

// 处理磁盘时间范围变化
const handleDiskTimeRangeChange = () => {
  getChartData('disk', diskTimeRange.value)
}

// 处理网络时间范围变化
const handleNetworkTimeRangeChange = () => {
  getChartData('network', networkTimeRange.value)
}

// 刷新数据
const refreshData = async () => {
  try {
    refreshing.value = true
    await getSystemInfoData()
    await getChartData('cpu', cpuTimeRange.value)
    await getChartData('memory', memoryTimeRange.value)
    await getChartData('disk', diskTimeRange.value)
    await getChartData('network', networkTimeRange.value)
  } catch (error) {
    console.error('刷新数据失败', error)
  } finally {
    refreshing.value = false
  }
}

// 定时刷新数据
const startRefreshTimer = () => {
  refreshTimer = setInterval(() => {
    refreshData()
  }, 60000) // 每分钟刷新一次
}

// 停止定时刷新
const stopRefreshTimer = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

onMounted(async () => {
  await refreshData()
  startRefreshTimer()
})

onUnmounted(() => {
  stopRefreshTimer()
})
</script>

<style lang="scss" scoped>
.app-container {
  .stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
  }
  
  .chart-container {
    margin-bottom: 20px;
    
    .chart-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
      gap: 20px;
      margin-bottom: 20px;
      
      .chart-card {
        background: var(--el-bg-color-overlay);
        border-radius: var(--el-border-radius-base);
        box-shadow: var(--el-box-shadow-lighter);
        padding: 20px;
        
        .chart-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          
          .chart-title {
            font-size: 16px;
            font-weight: bold;
            color: var(--el-text-color-primary);
          }
          
          .chart-actions {
            display: flex;
            align-items: center;
          }
        }
        
        .chart-content {
          height: 300px;
        }
      }
    }
  }
  
  .info-container {
    margin-bottom: 20px;
    
    .info-row {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
      gap: 20px;
      margin-bottom: 20px;
      
      .info-card {
        height: 100%;
      }
    }
  }
  
  .refresh-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>